package com.example.mail;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.MessageCodes;
import com.example.R;
import core.model.Game;
import core.util.Logger;

public class MailReplayActivity extends Activity {

    private LinearLayout mailReplayLayout;
    private MailManager mailManager;
    private Game game;
    private String selectedFrom;
    private String selectedMailType;
    private boolean answerToPrivate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mailreplay);

        Bundle bundle = this.getIntent().getExtras();

        selectedFrom = bundle.getString("from");
        game = (Game) bundle.getSerializable("game");
        selectedMailType = bundle.getString("selectedMailType");

        TextView from = (TextView) findViewById(R.id.mailReplayFrom);
        from.setText(from.getText() + selectedFrom);

        mailManager = new MailManager(this, game, handler);
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MessageCodes.Mail.SENDING_COMPLETE:
                    Logger.debug("MailReplayActivity", "Mail sending was complete without any problems.");
                    back();
                    break;

                case MessageCodes.Mail.SENDING_NOT_COMPLETE:
                    Logger.debug("MailReplayActivity", "Mail sending was not complete.");
                    break;
            }

        }
    };

    private void back() {
        finish();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mailReplayMenuSend:
                if (isAnswerToPrivate()) {
                    TextView content = (TextView) findViewById(R.id.mailReplayContent);
                    mailManager.sendMessage(selectedFrom, content.getText().toString());
                }

                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mailreplaymenu, menu);
        return true;
    }

    public boolean isAnswerToPrivate() {
        return "private".equalsIgnoreCase(selectedMailType);
    }
}
